#include <shader.h>		
#include <stdio.h>
#include <string.h>

Shader::Shader()
{
	log = NULL;
	id = 0;
}

Shader::~Shader()
{
	if (log != NULL)
	{
		delete [] log;
		log = NULL;
	}

	if (id > 0)
		glDeleteShader(id);
}

void Shader::load(const char *file, GLenum type)
{
	id = glCreateShader(type);
	if (id == 0)
		return;

	FILE * fp;

	fp = fopen(file, "r");

	if (fp == NULL)
	{
		printf("FAILE FILE\n");
		return;
	}
	else
	printf("***File success\n");


	fseek(fp, 0, SEEK_END);
	long lSize = ftell(fp);
	size_t result;
	rewind(fp);

	char * buffer = new char[lSize];
	memset(buffer, '\0', lSize);
	result = fread(buffer, 1, lSize, fp);

	fclose(fp);

	glShaderSource(id,  1, (const char **)&buffer, NULL);

	delete [] buffer;
	buffer = NULL;

	glCompileShader(id);

	glGetShaderiv(id, GL_COMPILE_STATUS, &compiled);

	if (!compiled)
	{
		GLint infoLen = 0;

		glGetShaderiv(id, GL_INFO_LOG_LENGTH, &infoLen);

		if (infoLen > 1)
		{
			log = new char[infoLen];
			glGetShaderInfoLog(id, infoLen, NULL, log);
		}
		glDeleteShader(id);
	}
}

char * Shader::getLog()
{
	return log;
}
